<template>
  <div v-loading.fullscreen.lock="uploadLoading">
    <c-r-m-list-head
      :search.sync="search"
      :crm-type="crmType"
      :create-fun="createClick"
      title="总部余额"
      main-title="新建充值"
      @on-handle="listHeadHandle"
      @on-export="exportInfos"
      :showSearch="false"
    >
      <el-menu
        slot="icon"
        ref="elMenu"
        :default-active="crmType"
        mode="horizontal"
        active-text-color="#2362FB"
        @select="menuSelect"
      >
        <el-menu-item
          v-for="(item, index) in menuItems"
          :key="index"
          :index="item.path"
        >
          <img :src="item.icon" />
          <span>{{ item.title }}</span>
        </el-menu-item>
      </el-menu>
    </c-r-m-list-head>
    <div
      v-empty="!crm.headquartersBusinessBalance.index"
      xs-empty-icon="nopermission"
      xs-empty-text="暂无权限"
      class="crm-container"
    >
      <c-r-m-table-head
        ref="crmTableHead"
        :crm-type="crmType"
        @handle="handleHandle"
        @scene="handleScene"
      >
        <slot name="custom">
          <div class="initTable_search">
            <span>部门：</span>
            <xh-structure-cell-mul
              radio
              class="xh-structure-cell"
              @valueChange="structureChangeBusiness"
              type="1"
              v-if="showDept"
              v-loading="deptLoading"
              ref="structurecell"
            />
          </div>
          <el-button
            type="primary"
            class="filter-button"
            icon="wk wk-screening"
            @click="searchTable"
            >搜索</el-button
          >
        </slot>
      </c-r-m-table-head>
      <el-table
        v-loading="loading"
        id="crm-table"
        :row-height="40"
        :data="list"
        :height="tableHeight"
        :cell-class-name="cellClassName"
        :header-cell-class-name="headerCellClassName"
        row-key="putinMoneyId"
        class="n-table--border"
        use-virtual
        stripe
        border
        highlight-current-row
        style="width: 100%"
        @row-click="handleRowClick"
        @sort-change="sortChange"
        @header-dragend="handleHeaderDragend"
        @selection-change="handleSelectionChange"
      >
      <el-table-column
        label="序号"
         type="index"
        >
        </el-table-column>
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :fixed="index == 0"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="fieldFormatter"
          :sortable="item.prop != 'id' ? 'custom' : false"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <template v-if="item.prop == 'checkStatus'">
              <span
                :style="getStatusStyle(scope.row.checkStatus)"
                class="status-mark"
              />
              <span>{{ getStatusName(scope.row.checkStatus) }}</span>
            </template>
            <template v-else>
              {{ item.prop=='id'? '':fieldFormatter(scope.row, scope.column) }}
            </template>
          </template>
        </el-table-column>
        

        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          width="60"
          v-if="crm[crmType].update"
        >
          <template slot-scope="scope">
            <p class="tableoption">
              <span @click="createClick(scope.row)">编辑</span>
            </p>
            <!-- | <span>删除</span> -->
          </template>
        </el-table-column>
        <!-- <el-table-column :resizable="false" fixed="right" width="40">
          <template slot="header" slot-scope="slot">
            <field-set :crm-type="crmType" @change="setSave" />
          </template>
        </el-table-column> -->
        <wk-empty
          slot="empty"
          :props="{
            buttonTitle: '新建充值',
            showButton: saveAuth,
          }"
          @click="createClick"
        />
      </el-table>
      <div class="p-contianer">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          :total="total"
          :pager-count="5"
          class="p-bar"
          background
          layout="prev, pager, next, sizes, total, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 相关详情页面 -->
    <roi-detail
      v-if="showDview"
      :id="rowID"
      class="d-view"
      @handle="handleHandle"
      @hide-view="showDview = false"
    />
    <div class="addView" v-if="addView">
      <div class="addView-top">
        <span>{{ isbianji ? "编辑充值" : "新建充值" }}</span>
        <span @click="closeClick">×</span>
      </div>
      <p class="addView-tit">基本信息</p>
      <div class="addView-content">
        <div class="addView-item">
          <p>组织</p>
          <xh-structure-cell
            radio
            class="xh-structure-cell"
            @value-change="structureChange($event)"
          />
        </div>
        <div class="addView-item">
          <span>充值金额</span>
          <el-input
            v-model="tfjeinput"
            maxlength="9"
            type="number"
            clearable
            onkeyup="value=value.replace(/-\d,'')"
          ></el-input>
        </div>

        <div class="addView-item">
          <p>充值日期</p>
          <el-date-picker
            v-model="datevalue"
            type="datetime"
            placeholder="选择日期"
          ></el-date-picker>
        </div>

        <div class="addView-item">
          <p>充值截图</p>
          <el-upload
            action="#"
            :on-preview="handlePreview"
            :on-success="uploadSuccess"
            :on-remove="handleRemove"
            :http-request="selectVideo"
            multiple
            accept="image/png , image/jpg, image/jpeg, image/gif"
            :limit="9"
            list-type="picture"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过9张
            </div>
          </el-upload>
        </div>
      </div>
      <div class="addViewbtn">
        <el-button @click="closeClick" size="mini">取消</el-button>
        <el-button
          @click.native="addClick(true)"
          type="primary"
          plain
          size="mini"
          >保存</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import TableMixin from "@/views/crm/mixins/Table";
import request from "@/utils/request";
import CreateSections from "@/components/CreateSections";
import WkApprovalFlowApply from "@/components/Examine/WkApprovalFlowApply";
import WkApprovalFlowApplyMixin from "@/components/Examine/mixins/WkApprovalFlowApply";
import { floatAdd } from "@/utils";
import { crmAllianceBusinessQueryByIdAPI } from "@/api/crm/allianceBusiness";
import { adminFileDeleteByIdAPI } from "@/api/admin/file";
import XhStructureCellMul from "@/components/CreateCom/XhStructureCellMul";
import XhStructureCell from "@/components/CreateCom/XhStructureCell";


// import CRMAllDetail from "../components/CRMAllDetail";
import RoiDetail from "./Detail";

export default {
  /** 学员管理 的 线索列表 */
  name: "headquartersBusinessBalance",
  components: {
    CreateSections,
    WkApprovalFlowApply,
    RoiDetail,
    XhStructureCellMul,
    XhStructureCell,
    // CRMAllDetail,
  },
  inject: ["reload"],
  mixins: [TableMixin, WkApprovalFlowApplyMixin],

  data() {
    return {
      crmType: "headquartersBusinessBalance",
      createShow: false,
      tfvalue: "",
      tfoptions: [],
      tfjeinput: "0", //投放金额
      sjtfjeinput: "0", //实际投放
      // kcinput: "", //课程期数
      datevalue: "", //投放日期
      addView: false,
      // selectView: false,
      // radioVal: "1",
      edit: 0, //修改id
      tfvalue_s: "", //搜索平台
      tfvalue_ses:"",//大类
      tfoptionses: ["电商美工","手绘插画","影视后期"],
      kcinput_s: "", //搜索课程期数
      datevalue_s: "", //搜索投放日期
      deptIds_s: [],
      crmRoiSearchBO: {}, //搜索
      wkFlowList: [],
      flowRemarks: "",
      putinCompensateMoney: "0",
      putinRebatesMoney: "0",
      rollinmoney: "0",
      rolloutmoney: "0",
      fileList: [],
      //fileList: [{name: '', url: ''}],
      remark: "",
      filevalue: "",
      uploadRe: 0,
      fName: "",
      moneyData: null,
      resNum: 0, //回调次数
      fileUploadList: [],
      isbianji: false,
      fileListedit: [],
      uploadLoading: false,
      showDept: true,
      deptLoading: false,
      deptreArr: [], //选中部门回显
      formNum: 0,
      avgPrice: 0,
      deptId: 0,
    };
  },
  computed: {
    moneyPageData() {
      if (!this.moneyData || JSON.stringify(this.moneyData) == "{}") {
        return null;
      }

      if (this.selectionList.length == 0) {
        return this.moneyData || {};
      } else {
        let money = 0.0;
        for (let index = 0; index < this.selectionList.length; index++) {
          const element = this.selectionList[index];
          // 1 审核通过的
          if (element.checkStatus == 1) {
            money = floatAdd(money, parseFloat(element.money));
          }
        }
        return {
          receivablesMoney: money.toFixed(2),
        };
      }
    },
    menuItems() {
      const temp = [];
      if (this.crm && this.crm.roiMoney) {
        temp.push({
          title: "总部余额",
          path: "headquartersBusinessBalance",
          icon: require("@/assets/img/crm/roiMoney.png"),
        });
      }

      return temp;
    },
  },

  created() {
    console.log(",,,,,,,,,,,")
    // this.debouncedSaveField = debounce(300, this.addClick);
  },
  mounted() {},
  deactivated: function () {
    if (this.$refs.elMenu) {
      this.$refs.elMenu.activeIndex = this.crmType;
    }
  },
  methods: {

    //计算消耗金额
    calculateXiaoHao(){
      console.log(this.formNum);
      console.log(this.avgPrice);
      this.sjtfjeinput = this.formNum * this.avgPrice;
    },
    structureChangeBusiness(e) {
      if (e.value.length > 0) {
        this.deptIds_s = e.value;
      } else {
        this.deptIds_s = [];
      }
    },
    structureChange(e) {
      this.deptId = e.value[0].deptId;
    },
    /**
     * 左侧菜单选择
     */
    menuSelect(key, keyPath) {
      this.$emit("menu-select", key, keyPath);
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === "deptName") {
        return "can-visit--underline can-visit--bold";
      } else {
        return "";
      }
    },

    headerCellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === "putinPlatform") {
        return "header-can-visit-backgroud";
      }
      return "";
    },

    createClick(row) {
      if (row) {
        console.log(row);
        this.isbianji = true;
        this.tfjeinput = row.topUpPrice;
        this.datevalue = row.topUpDate;
        this.deptId = row.deptId;
        this.edit = row.id;
        this.fName = row.topUpFileName;

        (row.id).then((res) => {
          this.filevalue = res.data.batchId;
          var fileListLength = res.data.fileList.length;
          this.fileList = [];
          for (var i = 0; i < fileListLength; i++) {
            if (i < fileListLength) {
              this.fileList.push({
                name: res.data.fileList[i].name,
                // fileId: res.date.fileList[i].fileId,
                url:
                  "http://crmfile.hanpinedu.com/" + res.data.fileList[i].path,
              });
              this.fileListedit.push(res.data.fileList[i].fileId);
            }
          }
          if (fileListLength > 0) this.filevalue = res.data.fileList[0].batchId;
        });

        this.addView = true;
      } else {
        this.clearData();
        this.edit = 0;
        this.addView = true;
        // this.selectView = true;
        this.isbianji = false;
      }
    },
    // 关闭新建
    closeClick() {
      this.addView = false;
      this.uploadLoading = false;
      this.clearData();
    },
    clearData() {
      this.tfjeinput = "0";
      this.datevalue = "";
      this.edit = 0;
      this.fileList = [];
      this.fName = "";
    },
    addClick(flag) {
      var id = this.edit;
      var ftjeinput = this.tfjeinput;
      // var kc = this.kcinput;
      var date = this.datevalue;
      var entity = {
        deptId: this.deptId,
        topUpPrice: this.tfjeinput,
        topUpDate: this.datevalue,
        batchId: this.filevalue,
        topUpFileName: this.fName,
      };
      var url = "crmAllianceBusiness/" + (id === 0 ? "add" : "update");
      if (id != 0) {
        //修改
        entity.id = id;
      }
      var crmModel = {
        entity: entity,
      };
      request({
        url: url,
        method: "post",
        data: crmModel,
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
        },
      }).then((res) => {
        this.$alert("操作成功", "系统提示", {
          confirmButtonText: "确定",
          callback: (action) => {
            this.reload();
          },
        });
      });
    },
    //删除图片
    handleRemove(res, file, fileList) {
      const urlArr = this.fileList.map((key) => key.url);
      const idx = urlArr.indexOf(res.url);
      const fileId = this.fileListedit[idx];
      console.log(fileId);
      adminFileDeleteByIdAPI(fileId).then((res) => {
      });
    },
    // 上传成功时的钩子
    uploadSuccess(res, file, fileList) {
      // console.log(res,file,fileList, 987);
    },
    handlePreview(file) {},
    selectVideo(file, fileList) {
      this.uploadLoading = true;
      var param = new FormData();
      Object.keys(file).forEach((key) => {
        param.append(key, file[key]);
      });
      this.uploadRe += 1;
      if (this.uploadRe == 1) {
        if (this.isbianji) param.set("batchId", this.filevalue);
        this.fileRe(param);
        clearInterval(this.setIntervalModel);
        // this.uploadLoading = false;
        // setTimeout(() => {
        //   this.uploadLoading = false;
        // }, 2000);
      } else {
        this.fileUploadList.push(param);
        if (this.fileUploadList.length == 0) {
          clearInterval(this.setIntervalModel);
          // this.uploadLoading = false;
          return;
        }
        this.setIntervalModel = setInterval(() => {
          if (this.fileUploadList.length > 0) {
            if (this.uploadRe != this.resNum && this.resResult) {
              const len = this.fileUploadList.length;
              let obj = this.fileUploadList[len - 1];
              obj.set("batchId", this.filevalue);
              this.fileRe(obj);
              this.fileUploadList.length = len - 1;
              // this.fileUploadList.push(param);
            } else {
              if (this.uploadRe > 1 && this.resNum > 1) {
                this.uploadRe = 0;
                this.resNum = 0;
              }
              // this.uploadLoading = false;
              clearInterval(this.setIntervalModel);
            }
          } else {
            if (this.uploadRe > 1 && this.resNum > 1) {
              this.uploadRe = 0;
              this.resNum = 0;
            }
            // this.uploadLoading = false;
            clearInterval(this.setIntervalModel);
            return;
          }
        }, 800);
      }
      setTimeout(() => {
          this.uploadLoading = false;
        }, 2500);
    },
    fileRe(param) {
      this.resResult = false;
      request({
        url: "adminFile/upload",
        method: "post",
        data: param,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then((res) => {
        this.resResult = true;
        this.resNum += 1;
        this.filevalue = res.data.batchId;
        this.fName = res.data.name + "," + this.fName;
        this.uploadSuccess(res);
      });
    },
  },

  created() {

  },
};
</script>

<style lang="scss" scoped>
@import "@/views/crm/styles/table.scss";

/deep/.table-option-view {
  display: none !important;
}
/deep/ .el-table th.is-leaf{
  text-align: center;
}
/deep/  .el-table__body td{
  text-align: center;
}
.initTable_search {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-right: 20px;
  padding: 0 10px;
  // overflow: hidden;

  span {
    white-space: nowrap;
  }
  .el-select{
    width: 80%;
  }
}

/deep/ .el-table{
  margin-top: 40px;
}
/deep/ .block_reshow{
  left: -3vw !important;
}

.tableoption {
  span {
    cursor: pointer;

    &:hover {
      text-decoration: underline;
    }
  }
}

.addView {
  position: fixed;
  overflow-y: scroll;
  top: 80px;
  left: 18vw;
  width: 60vw;
  border: 1px solid #bbb;
  z-index: 999;
  height: 70vh;
  background-color: #fff;

  .addView-tit {
    font-size: 18px;
    margin: 31px 0 13px 59px;

    &::before {
      content: "*";
    }
  }

  p {
    color: #000000;
  }

  .addView-content {
    padding: 0 109px 0 87px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    flex-wrap: wrap;
    .addView-item {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-bottom: 26px;

      span {
        font-size: 15px;
        width: 120px;
        margin-right: 7px;
        display: block;

        &::before {
          content: "*";
          color: #fd0707;
        }
      }
      p {
        font-size: 15px;
        width: 120px;
        margin-right: 7px;
        display: block;
      }
      .el-select,
      .el-input,
      .el-textarea {
        width: 257px;
      }
    }
  }

  .addViewbtn {
    margin: 50px 62px 41px 673px;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;

    button {
      width: 96px;
      height: 40px;
      font-size: 14px;
      border: 1px solid #bbb;
      cursor: pointer;

      &:first-child {
        background-color: #fff;
        color: #000;
        margin-right: 18px;
      }

      &:last-child {
        background-color: #0083ff;
        color: #fff;
      }
    }
  }
}
.addView-top {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  border-bottom: 1px solid #bbbbbb;
  align-items: center;

  span {
    color: #101010;
  }

  span:first-child {
    font-size: 20px;
    padding: 7px 0 9px 22px;
  }

  span:last-child {
    font-weight: bold;
    font-size: 20px;
    margin: 10px 13px 0 0;
    cursor: pointer;
  }
}
.selectView {
  position: absolute;
  overflow-y: scroll;
  top: 100px;
  left: 25vw;
  width: 480px;
  border: 1px solid #bbb;
  z-index: 99;
  height: 220px;
  background-color: #fff;
  .radio_box {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 60%;
  }
}
.selectViewbtn {
  display: flex;
  button {
    margin-left: auto;
    margin-right: 30px;
  }
}

.money-bar1 {
  display: inline-block;
  color: #99a9bf;
  line-height: 44px !important;
  margin-left: 10px;
}

/deep/ .el-radio__label {
  font-size: 15px;
}
/deep/ .el-radio__input.is-checked + .el-radio__label {
  color: #2362fb !important;
}
</style>
